package com.andy.qi.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.andy.qi.util.StrUtils;

@Service
public class TokenMgr {
    Map<String, TokenInfo> tokens = new HashMap<>();
    Map<String, String> users = new HashMap<>();
    public String createToken(String userid, int lifeTime) {
        String token = users.get(userid);
        if(token != null){
            delToken(token);
        }

        long time = System.currentTimeMillis();
        token = StrUtils.md5(userid + "!@#$%^&" + time);
        tokens.put(token, new TokenInfo(userid, time, lifeTime));
        users.put(userid, token);
        return token;
    }

    public String getToken(String userId) {
        return users.get(userId);
    }

    public String getUserID(String token){
        return tokens.get(token).userId;
    }

    public boolean isTokenValid(String token){
        TokenInfo info = tokens.get(token);
        if(info == null){
            return false;
        }
        if(info.time + info.lifeTime < System.currentTimeMillis()){
            return false;
        }
        return true;
    }

    public void delToken(String token){
        TokenInfo info = tokens.get(token);
        if(info != null){
            tokens.remove(token);
            users.remove(info.userId);
        }
    }
    
    private static class TokenInfo {
        String userId;
        long time;
        int lifeTime;
        
        public TokenInfo(String userId, long time, int lifeTime) {
            this.userId = userId;
            this.time = time;
            this.lifeTime = lifeTime;
        }
        
    }
}
